package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.Emtity.Category;
import com.itheima.Emtity.Dish;
import com.itheima.Emtity.Setmeal;
import com.itheima.common.CustomException;
import com.itheima.mapper.CategoryMapper;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.EmployeeService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


//这是一个完整的实现方法,接口那个只实现一半CategoryService.另一半在 ServiceImpl
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 根据id删除,但是要判断一下,
     *
     * @param ids 我们先获得主表要删除的id,之后再从表查看关联的菜品.(外键)
     */
    @Override
    public boolean remove(Long ids) {
        // 查询当前分类是否关联了菜品,如果已经关联,
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Dish::getCategoryId, ids);

        int count = dishService.count(lambdaQueryWrapper);

        //select count(*) from dish  where category_id=?
//        计算我们要删除的分类 ,是否有关联的菜品.
        if (count > 0) {
//            有关联
            //抛出异常
            throw new CustomException("有关联的菜品,无法删除");
        }

        LambdaQueryWrapper<Setmeal> SetmealId = new LambdaQueryWrapper();
        SetmealId.eq(Setmeal::getCategoryId, ids);
        int count1 = setmealService.count(SetmealId);
        if (count1 > 0) {
//            有关联的套餐
            throw new CustomException("有关联的套餐分类,无法删除.");
        }
        // 查询当前分类是否关联了套餐,如果已经关联,

        //没有连接的数据,则删除分类
        boolean b = super.removeById(ids);
        return b;
    }
}
